angular.module('money', []).controller('moneyCtrl', ['$scope', 'httpService', '$localStorage', '$rootScope', 'alertmsg', '$location', 'confirmservice', '$state', '$timeout', function($scope, httpService, $localStorage, $rootScope, alertmsg, $location, confirmservice, $state, $timeout) {
        $scope.type="income";
       	//是否显示折线图
       	$scope.lineShow=false;
       	//下拉框数据
        $scope.timeItem=[{
        		id:1,
        		name:"最近一个月"
        },{
        		id:3,
        		name:"最近三个月"
        },{
        		id:6,
        		name:"最近半年"
        },{
        		id:12,
        		name:"最近一年"
        }];
         //钱包对象
        $scope.moneyObj={
        		timeState:$scope.timeItem[0].id,
        		timeEnd:null
        };
        if (!$localStorage.user && !$localStorage.mutian_token) {
            $state.go('login');
        }
        //获取用户
        function getPersion() {
            httpService.query('web/users/' + $localStorage.user.id).then(function(res) {
                if (res.code == 200) {
                		console.log(res.user);
                    $localStorage.user = $rootScope.user = res.user;
                }
            })
        };
        getPersion();
        //下拉框处理
        $scope.timeChange=function(){
//      		switch($scope.moneyObj.timeState) {
//				case 1:
//					$scope.moneyObj.timeEnd = 1;
//					break;
//				case 3:
//					$scope.moneyObj.timeEnd = 0;
//					break
//				case 6:
//					$scope.moneyObj.timeEnd = 0;
//					break
//				case 12:
//					$scope.moneyObj.timeEnd = 1;
//					break
//			}
        		$scope.getPayments();
        }
        //收入和支出
        $scope.monyChange=function(type){
        		if(type==1){
        			$scope.type="income"
        		}else{
        			$scope.type="expense"
        		}
        		$scope.getPayments();
        }
        //明细
        $scope.toMoneyDetail = function(type) {
        		if(type==2){
        			$scope.type=2;
        		}else if(type==3){
        			$scope.type=3;
        		}
        		$state.go('mine.moneyDetail',{start:$scope.moneyObj.timeState,end:$scope.moneyObj.timeEnd,type:$scope.type});	
        };
        //获取钱包
        $scope.getPayments = function() {
        		var parameter={
        			type:$scope.type,
        			start:$scope.moneyObj.timeState,
//      			end:$scope.moneyObj.timeEnd
        		}
        		console.log(parameter);
            httpService.query('web/payments/fetch_payments',parameter).then(function(res) {
                if (res.code == 200) {
                		console.log(res);
                		$scope.moneyList=res;
                		if($scope.moneyList.yesterday_income==null || $scope.moneyList.yesterday_income==""){
                			$scope.moneyList.yesterday_income=0;
                		}
                		if($scope.moneyList.red_count==null || $scope.moneyList.red_count==""){
                			$scope.moneyList.red_count=0;
                		}
                		if($scope.moneyList.accumulative_count==null || $scope.moneyList.accumulative_count==""){
                			$scope.moneyList.accumulative_count=0;
                		}
                		if($scope.moneyList.line_payments.length==0){
                			notPieId();
                		}else{
	            			//饼状图
	                		$scope.pieObj=res.cart_payments;
	                		pieData(function(common,dataList,subtext){
	                			pieImg(common,dataList,subtext);
	                		});
	            			//折线图
	                		$scope.lineList=res.line_payments;
	                		lineData(function(transverse,longitudinal,mon){
		                		lineImg(transverse,longitudinal,mon);
	                		})
                		}
                } else {
                    alertmsg(res.msg);
                }
            });
        }
        $scope.getPayments();
        //饼状图数据处理
        function pieData(callback){
        		var common=0;
        		var dataList=[];
        		var subtext=null;
        		var dataObj={
        			value:null,
        			name:null
        		}
        		dataList=[];
//      		安装劳务费-650提现-1100测量劳务费0
        		for(var i in $scope.pieObj){
        			if($scope.type=="expense"){
        				subtext="总支出(元)";
        				if($scope.pieObj[i]!=0){
        					common=common+parseInt(($scope.pieObj[i]/100).toString().substring(1,100));
        				}
        			}else{
        				subtext="总收入(元)"
        				common=common+$scope.pieObj[i]/100;
        			}
    				dataObj.value=$scope.pieObj[i]/100;
    				dataObj.name=i;
    				dataList.push(angular.copy(dataObj));
        		}
        		console.log(common);
			callback(common.toFixed(2),dataList,subtext);
        };
        //折线图数据处理
        function lineData(callback){
        		var transverse=[];    //横坐标
        		var longitudinal=[];  //纵坐标
        		var mon;
        		var day;
        		angular.forEach($scope.lineList,function(res){
        			for(var j in res){
        				longitudinal.push(res[j]/100);
        				mon=j.substring(5,7);
        				day=j.substring(8,10);
        				j=mon+"/"+day;
        				transverse.push(j);
        			}
        		})
        		callback(transverse,longitudinal,mon);
        };
        //饼状图
        function pieImg(common,dataList,subtext){
        		var myChart = echarts.init(document.getElementById('pieId')); 
			var option = {
    				title : {
			        text: common,
			        subtext: subtext,
			        x:0
			    },
			    //提示框
			    tooltip : {
			    		show:false,
			        trigger: 'item',
			        formatter: "{a} <br/>{b} : {c} ({d}%)"	
			    },
			    calculable : false, 
			    series : [
			        {
//			            name:'收入',
			            type:'pie',
			            radius : '50%',
			            data:dataList,
			            center: ['52%', '65%'],
//			            lableLine:{
//			                normal:{
//			                    show:true,
//			                    length:'2',
//			                    length2:'10'
//			                }
//			            }
			        }
		    		]
			};
			myChart.setOption(option); 
			window.onresize = myChart.resize;
        }
        //饼状图无数据时
        function notPieId(){
       	 	var myChart = echarts.init(document.getElementById('pieId')); 
       	 	var myCharts= echarts.init(document.getElementById('lineId')); 
       	 	var option = {
			    text: '暂无数据',
			    effect:'bubble',
			    effectOption : {
			        effect: {
			            n: 2 //气泡个数为0
			        }
			    }
			};
			myChart.setOption(option); 
			window.onresize = myChart.resize;
			myCharts.setOption(option); 
			window.onresize = myChart.resize;
        }
        //折线图
        function lineImg(transverse,longitudinal,mon){
        		var myChart = echarts.init(document.getElementById('lineId')); 
        		var	option = {
			    calculable :false,
			    tooltip : {
			    		show:false,
			        trigger: 'axis',
			        formatter: "Temperature : <br/>{b} : {c}",
			    },
			    grid:{
                    x:50,
                    y:45,
                    x2:5,
                    y2:20,
                    borderWidth:1
                },
			    xAxis : [
			        {
			            type : 'category',
			            data:transverse
			        }
			    ],
			    yAxis : [
			        {
//			        		name:mon+"月收入",
			            type : 'value',
			        }
			    ],
			    tooltip : {
			    		show:true,
			        trigger: 'item',
			        formatter: "{a} <br/>{b} : {c} ({d}%)"	
			    },
			    series : [
			        {
			            type:'line',
			            tooltip:false,
			            smooth:true,
			            itemStyle: {
			                normal: {
			                    lineStyle: {
			                        shadowColor : 'rgba(0,0,0,0.4)'
			                    }
			                }
			            },
			            center: ['50%', '50%'],
			            data:longitudinal
			        }
			    ]
			};
			myChart.setOption(option); 
        }
        
        
        
        
        
        
        
        // 付款
//      $scope.paypayment = function(payment) {
//          if (payment.trade_status == 'pending') {
//              confirmservice('是否确认支付？').then(function(bool) {
//                  if (bool) {
//                      httpService.query('web/payments/payment', { id: payment.id }, 'post').then(function(res) {
//                          if (res.code == 200) {
//                              pingpp.createPayment(res.charge, function(result, err) {
//                                  if (result == "success") {
//                                      $scope.getOrderById();
//                                  } else if (result == "fail") {
//                                      console.log("fail");
//                                  } else if (result == "cancel") {
//                                      console.log("cancel");
//                                  }
//                              });
//                          } else {
//                              alertmsg(sres.msg);
//                          }
//                      });
//                  }
//              });
//          }
//      };

//      function sendNotify(no, url) {
//          httpService.query('notify_success', { order_no: no }, 'post').then(function(res) {
//              window.location.href = url;
//              getPersion();
//          }, function() {
//              getPersion();
//          });
//      }
//
//      if ($location.search().trade_status == 'TRADE_SUCCESS') {
//          var url = $location.absUrl().split('?')[0];
//          sendNotify($location.search().out_trade_no, url);
//      } else {
//          getPersion();
//      }
//
//      var mydate = new Date();
//      var week = mydate.getDay();
		//折线图
//      function salesLoad() {
//          $(function() {
//              $("#moneyhighchart").highcharts({
//                  title: {
//                      text: '收益率',
//                      x: -20 //center
//                  },
//                  chart: {
//                      zoomType: 'xy',
//                      type: 'area'
//                  },
//                  exporting: {
//                      enabled: false
//                  },
//                  credits: {
//                      enabled: false
//                  },
//                  xAxis: {
//                      tickmarkPlacement: 'on',
//                      gridLineWidth: '1px',
//                      // gridLineColor: '#000',
//                      categories: ['12/29', '12/30', '1/2', '1/3', '1/4', '1/5', '1/6'],
//                      // plotBands: [{ // visualize the weekend
//                      //     from: 4.5,
//                      //     to: 6.5,
//                      //     color: 'rgba(68, 170, 213, 0)'
//                      // }]
//                  },
//                  yAxis: {
//                      tickPositions: [0, 20, 40, 60, 80, 100],
//                      title: {
//                          text: ''
//                      },
//                  },
//                  tooltip: {
//                      valueSuffix: '%'
//                  },
//                  legend: {
//                      layout: 'vertical',
//                      align: 'right',
//                      verticalAlign: 'middle',
//                      borderWidth: 0
//                  },
//                  plotOptions: {
//                      // colorByPoint: true,
//                      // areaspline: {
//                      //     color: '#rgba(255, 186, 0, 0.2)',
//                      //     lineColor: '#ffba00',
//                      //     fillOpacity: 0.2
//                      // }
//                  },
//                  series: [{
//                      name: '昨天',
//                      data: [14, 18, 30, 50, 80, 60, 0]
//                  }, {
//                      name: '今天',
//                      data: [0, 5, 8, 17, 22, 30, 24]
//                  }]
//              });
//          });
//      }
}]);
